﻿//*********************************************************

//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Microsoft Public License.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

//*********************************************************

using System;
using System.Diagnostics;
using System.IO;

///<summary>
///Class Name: ODataTestGen.T4Helpers
///T4Helpers.RunT4Template uses TextTemplate.exe to generate the Unit Test File (*.cs) using the provided T4 Templates (*.tt)
///DirectoryNotFoundException is thrown if there is no available version of TextTemplating installed in the computer
///</summary>

namespace ODataTestGen
{
    static class T4Helpers
    {
        public static void RunT4Template(string templateFileName, string outputFile, string workingDirectory)
        {
            string programFilesDir = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
            if (programFilesDir == null)
                programFilesDir = Environment.GetEnvironmentVariable("ProgramFiles");
            string textTemplatesLocation = Path.Combine(programFilesDir, @"Common Files\microsoft shared\TextTemplating\");
            string[] textTransformExes = Directory.GetFiles(textTemplatesLocation, "TextTransform.exe", SearchOption.AllDirectories);
            if (textTransformExes.Length == 0)
            {
                throw new DirectoryNotFoundException("There is no TextTemplating installed under path \"" + textTemplatesLocation + "\".");
            }
            string textTransformExe = textTransformExes[0];   
         
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = textTransformExe;

            string templatePath = Path.Combine(Directory.GetCurrentDirectory() + "\\..\\..", templateFileName);
            templatePath = Path.Combine(Directory.GetCurrentDirectory(), templatePath);
            psi.Arguments = "-out \"" + outputFile + "\" \"" + templatePath + "\"";
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;
            psi.WorkingDirectory = workingDirectory;

            if (File.Exists(outputFile))
            {
                File.Delete(outputFile);
            }

            using (var process = Process.Start(psi))
            {
                process.WaitForExit();
                if (process.ExitCode != 0)
                {
                    throw new OperationCanceledException("Error occured when generating tests from template \'" + templateFileName + "\'.");
                }
            }
        }
    }
}
